import struct
import numpy as np
import os
import re

def loaddata(folder):
    binfile=open(folder, 'rb')
    binfile.seek(89)
    context=binfile.read(4)
    realContext=struct.unpack('2H',context)
    len = realContext[1] - realContext[0] + 1 #计算光谱长度
    binfile2 = open(folder, 'rb')
    binfile2.seek(328)
    context2 = binfile2.read(4 * 2 * len )
    realContext = struct.unpack(str(len*2)+'f', context2)
    #realContext = struct.unpack('3874f', context2)
    realContext = list(realContext)
    wave = realContext[:len]
    specture = realContext[len:]
    return wave, specture




def fileload(folder, savefolder, pattern, pattern2):
    if os.path.exists(savefolder):
        print('解密文件夹存在！')
    else:
        os.makedirs(savefolder)
    for filefolder in os.listdir(folder):
        mes = re.match(pattern, filefolder)
        if mes:
            print(filefolder)
            filefolderpath = os.path.join(folder, filefolder)
            savefile = os.path.join(savefolder, filefolder)
            if os.path.exists(savefile):
                print('文件夹存在！')
            else:
                os.makedirs(savefile)
            data = {}
            waves, sums, datas = [], [], []
            for file in os.listdir(filefolderpath):
                mes = re.match(pattern2, file)
                if mes:
                    wave, specture = loaddata(os.path.join(filefolderpath, file))
                    name = file.split('_')[0]
                    if len(specture) < 2048:
                        print('长度 = ', len(specture))
                        print(file)
                    if wave in waves:
                        pass
                    else:
                        waves.append(wave)
                        sums.append(sum(wave))
                    if name in data:
                        data[name].append(specture)
                    else:
                        data[name] = []
                        data[name].append(specture)
                else:
                    print('文件不匹配！')
            for key, value in data.items():
                print(len(value))
                datas.append(np.vstack(value).T)
            lis = np.array(sums)
            sorted_index = np.argsort(lis)
            sumss, wavess, datass = [], [], []
            print(sorted_index)
            for i in sorted_index:
                sumss.append(sums[i])
                wavess.append(waves[i])
                datass.append(datas[i])
            wavess = np.hstack(wavess).reshape(-1,1)
            '''lines = []
            for i in datass:
                line = i.shape[1]
                if line == 300:
                    lines.append(1)
                else:
                    continue
            if len(lines) < 5:
                continue'''
            datass = np.vstack(datass)
            print(wavess.shape)
            print(datass.shape)
            datasss = np.hstack((wavess, datass))
            savefiledata = os.path.join(savefile, 'Times_0.csv')
            np.savetxt(savefiledata, datasss, fmt='%.04f',delimiter=',')
            print('数据保存至：', savefiledata)
            del datass
            del wavess



if __name__ == '__main__':
    folder = r'I:\无设备编号\创谱未知样品\创谱20240221\颗粒'
    savefolder = r'I:\无设备编号\创谱未知样品\创谱20240221\颗粒\数据解密'
    pattern = 'l.*'
    pattern2 = '7.*'
    fileload(folder, savefolder, pattern, pattern2)